package cn.lyjuan.first.netty.demo._3_netty4.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;

import java.nio.charset.Charset;

public class ServerHandler extends ChannelInboundHandlerAdapter
{
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception
    {
        System.out.println("server receive connect");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
    {
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("server receive: " + new String(buf.toString(Charset.forName("UTF-8"))));

        Channel chl = ctx.channel();
        String res = "World";
        chl.write(Unpooled.copiedBuffer(res, Charset.forName("UTF-8")));
        System.out.println("server send: " + res);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception
    {
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)// 当读取完所有数据后，flush下缓存
        .addListener(ChannelFutureListener.CLOSE);// 当flush完成后，关闭channel
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception
    {
        cause.printStackTrace();

        ctx.close();
    }
}
